
const { db, command, cloud } = require(':share/webServer')
const useMidware = require(':utils/useMidware')
const { randomNum } = require(':utils/randomNum')
const checkJson = require(':utils/checkJson')
const fs = require('fs')

async function checkData(ctx, next)
{
    if (ctx.request.files.prize_picture === undefined)
        throw ({
            msg: 'prize_picture is required'
        })
    if (ctx.request.body.prize_name === undefined)
        throw ({
            msg: 'prize_name is required'
        })
    await next()
}

async function createPrize(ctx, next)
{
    const file = ctx.request.files.prize_picture
    const { prize_name } = ctx.request.body
    const now = new Date().valueOf()
    const filename = now.toString() + randomNum(0, 9).toString() + '.jpg'

    let rsp = await cloud.uploadFile({
        cloudPath: 'prize_pictures/' + filename,
        fileContent: fs.createReadStream(file.path)
    })

    let { fileID } = rsp
    rsp = await cloud.getTempFileURL({
        fileList: [fileID]
    })

    let { fileList: [{ tempFileURL }] } = rsp
    rsp = await db.collection('Prizes_info').where({
        name: 'max_prize_id'
    }).get()


    let max_prize_id = rsp.data[0].value
    rsp = await db.collection('Prizes').add({
        prize_id: max_prize_id,
        prize_name: prize_name,
        picture_url: tempFileURL
    })

    await db.collection('Prizes_info').where({
        name: 'max_prize_id'
    }).update({
        value: command.inc(1)
    })

    await db.collection('Prizes_info').where({
        name: 'prize_num'
    }).update({
        value: command.inc(1)
    })
    await next()
}

useMidware.post('/modules/adminPage/managePrize/newPrize', checkData)
useMidware.post('/modules/adminPage/managePrize/newPrize', createPrize)